
<!DOCTYPE html>
<html lang="en">
    <!--百度统计-->
    <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b94bd2699a7baf9292dd9cf571f7fbb9";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
    </script>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="keywords" content="Python,Django,Python教程,Django教程,教程,基础教程,Web开发,运维,自动化,博客,编程,软件,云计算,大数据,爬虫,
    人工智能,机器学习,神经网络" />
    <meta name="description" content="提供Python和Django的原创中文精品教程和博客,分享技术知识,传播新闻视点,提倡开源精神,让更多开发者从中受益。">
    <meta name="author" content="刘江,liujiang,大江东流">
    <title>
    
    django 关系类型字段 - 刘江的django教程
    
</title>
	
	<!-- core CSS -->
    <link href="/staticbootstrap.min.css" rel="stylesheet">
    <link href="/staticfont-awesome.min.css" rel="stylesheet">


    <link href="/staticmain.css" rel="stylesheet">

    <link href="/staticgithub.css" rel="stylesheet">
    <!--[if lt IE 9]>
    <script src="js/html5shiv.js"></script>
    <script src="js/respond.min.js"></script>
    <![endif]-->       
    <link rel="shortcut icon" href="/static/images/ico/favicon.ico">
    
    <link href="/staticcourse.css" rel="stylesheet">


</head><!--/head-->

<body class="homepage">

    <header id="header" class=" navbar-fixed-top">
        <div class="top-bar">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-6">
                        <div class="top-number">
                            <p><i class="fa fa-feed" aria-hidden="true"></i>&nbsp;
                            <strong style="color: red;">强烈推荐博主精心录制的Python及Django视频教程,<a href="/video/">详情点击</a>!</strong>
                            </p></div>
                    </div>
                    <div class="col-md-offset-3 col-md-3">
                        <span class="pull-left">分享：</span>
                        <!-- JiaThis Button BEGIN社会化分享工具 -->
                        <div class="jiathis_style_24x24">
                            <a class="jiathis_button_qzone"></a>
                            <a class="jiathis_button_tsina"></a>
                            <a class="jiathis_button_tqq"></a>
                            <a class="jiathis_button_weixin"></a>
                            <a class="jiathis_button_renren"></a>
                            <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
                        </div>

                        <!-- JiaThis Button END -->
                    </div>
                </div>
            </div><!--/.container-->
        </div><!--/.top-bar-->

		<nav class="navbar navbar-default navbar-inverse">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#my-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">刘江的博客及教程</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="my-navbar">
      <ul class="nav navbar-nav">
        <li><a href="/news/">新闻</a></li>
        <li><a href="/blog/">博客</a></li>
        <li><a href="/course/python/1">Python教程</a></li>
        <li><a href="2.html">Django教程</a></li>
        <li><a href="/video/">视频教程</a>
        <span class="badge" style="color: red;text-shadow:-1px 0 white,0 1px white,1px 0 white,0 -1px white; float: right;font-size: small;margin-left: -8px;">Hot!</span>
        </li>
      </ul>

      <form id="search-form" method="get" action="/blog/search/" class="navbar-form navbar-left collasped">
        <div class="form-group">
          <input type="text" name="keyword" class="form-control" placeholder="Search" required>
        </div>
        <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
      </form>

      <ul class="nav navbar-nav navbar-right">
          <li>
            
              <!--通过在login后添加next参数，让用户登录后返回先前的页面-->
            <a href="96.html">
            <span class="glyphicon glyphicon-log-in"></span>登录</a></li>
            
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

    </header><!--/header-->


    
    <div class="container-fluid main">
      <div class="row">

        <!-- 左侧目录栏 -->
        <div class="col-md-3">
          <div class="navbar-sider list-group-item">
            目&nbsp;录
            <hr />
            
                
                        
                            
                            <a href="2.html" class="list-group-item"><b>Django教程</b></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="84.html"
                               class="list-group-item"><strong>Django简介</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="85.html"
                               class="list-group-item"><strong>Django环境安装</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="86.html"
                               class="list-group-item"><strong>第一个Django应用</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="87.html"
                               class="list-group-item">Part 1：请求与响应</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="88.html"
                               class="list-group-item">Part 2：模型与管理后台</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="89.html"
                               class="list-group-item">Part 3：视图和模板</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="90.html"
                               class="list-group-item">Part 4：表单和类视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="91.html"
                               class="list-group-item">Part 5：测试</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="92.html"
                               class="list-group-item">Part 6：静态文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="93.html"
                               class="list-group-item">Part 7：自定义admin站点</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="94.html"
                               class="list-group-item"><strong>第一章：模型层model layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="95.html"
                               class="list-group-item">模型和字段</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="96.html"
                               class="list-group-item active">关系类型字段</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="97.html"
                               class="list-group-item">字段的参数</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="98.html"
                               class="list-group-item">多对多中间表详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="99.html"
                               class="list-group-item">模型的元数据Meta</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="100.html"
                               class="list-group-item">模型的继承</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="101.html"
                               class="list-group-item">用包来组织模型</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="129.html"
                               class="list-group-item">查询操作</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="130.html"
                               class="list-group-item">查询集API</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="131.html"
                               class="list-group-item">不返回QuerySets的API</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="132.html"
                               class="list-group-item">字段查询参数及聚合函数</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="133.html"
                               class="list-group-item"><strong>第二章：视图层view layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="182.html"
                               class="list-group-item">Django2.0 URL配置</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="134.html"
                               class="list-group-item">URL路由基础</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="135.html"
                               class="list-group-item">路由转发</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="136.html"
                               class="list-group-item">URL反向解析和命名空间</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="137.html"
                               class="list-group-item">视图函数及快捷方式</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="138.html"
                               class="list-group-item">HttpRequest对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="139.html"
                               class="list-group-item">QueryDict对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="140.html"
                               class="list-group-item">HttpResponse对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="141.html"
                               class="list-group-item">文件上传</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="142.html"
                               class="list-group-item">动态生成CSV文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="143.html"
                               class="list-group-item">动态生成PDF文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="144.html"
                               class="list-group-item"><strong>第三章：模版层Template layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="145.html"
                               class="list-group-item">Django模板语言详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="146.html"
                               class="list-group-item">Django内置模板标签</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="147.html"
                               class="list-group-item">Django内置模版过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="148.html"
                               class="list-group-item">特殊的标签和过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="149.html"
                               class="list-group-item">人类可读性</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="150.html"
                               class="list-group-item">自定义模板标签和过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="151.html"
                               class="list-group-item"><strong>第四章：Django表单</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="152.html"
                               class="list-group-item">使用表单</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="153.html"
                               class="list-group-item">Django表单API详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="154.html"
                               class="list-group-item">Django表单字段汇总</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="155.html"
                               class="list-group-item">表单的Widgets</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="156.html"
                               class="list-group-item">模型表单ModelForm</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="157.html"
                               class="list-group-item"><strong>第五章：Admin管理后台</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="158.html"
                               class="list-group-item">自定制Admin</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="159.html"
                               class="list-group-item">自定义Admin actions</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="160.html"
                               class="list-group-item">Admin文档生成器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="162.html"
                               class="list-group-item"><strong>第六章：Django 综合篇</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="163.html"
                               class="list-group-item">配置 Django</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="164.html"
                               class="list-group-item">核心配置项</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="165.html"
                               class="list-group-item">使用MySQL数据库</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="166.html"
                               class="list-group-item">django-admin和manage.py</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="167.html"
                               class="list-group-item">自定义django-admin命令</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="168.html"
                               class="list-group-item">会话session</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="169.html"
                               class="list-group-item">网站地图sitemap</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="170.html"
                               class="list-group-item">信号 signal</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="171.html"
                               class="list-group-item">序列化 serializers</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="172.html"
                               class="list-group-item">消息框架 message</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="173.html"
                               class="list-group-item">分页 Paginator</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="174.html"
                               class="list-group-item">聚合内容 RSS/Atom</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="175.html"
                               class="list-group-item">发送邮件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="176.html"
                               class="list-group-item">Django 日志</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="177.html"
                               class="list-group-item">Django与缓存</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="178.html"
                               class="list-group-item">认证系统 Authentication</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="179.html"
                               class="list-group-item">Django与CSRF 、AJAX</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="180.html"
                               class="list-group-item">Django 国际化和本地化</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="181.html"
                               class="list-group-item">部署 Django</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="102.html"
                               class="list-group-item"><strong>实战一：用户登录与注册系统</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="103.html"
                               class="list-group-item">1. 搭建项目环境</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="104.html"
                               class="list-group-item">2. 设计数据模型</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="105.html"
                               class="list-group-item">3. admin后台</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="106.html"
                               class="list-group-item">4. url路由和视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="107.html"
                               class="list-group-item">5. 前端页面设计</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="108.html"
                               class="list-group-item">6. 登录视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="109.html"
                               class="list-group-item">7. Django表单</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="110.html"
                               class="list-group-item">8. 图片验证码</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="111.html"
                               class="list-group-item">9. session会话</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="112.html"
                               class="list-group-item">10. 注册视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="113.html"
                               class="list-group-item">11.使用Django发送邮件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="114.html"
                               class="list-group-item">12. 邮件注册确认</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="115.html"
                               class="list-group-item">13. 使用Github管理项目</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="116.html"
                               class="list-group-item"><strong>实战二：CMDB之资产管理系统</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="117.html"
                               class="list-group-item">1.项目需求分析</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="118.html"
                               class="list-group-item">2.模型设计</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="119.html"
                               class="list-group-item">3.数据收集客户端</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="120.html"
                               class="list-group-item">4.Windows下收集数据</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="121.html"
                               class="list-group-item">5.Linux下收集数据</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="122.html"
                               class="list-group-item">6.新资产待审批区</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="123.html"
                               class="list-group-item">7.审批新资产</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="124.html"
                               class="list-group-item">8.已上线资产信息更新</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="125.html"
                               class="list-group-item">9.前端框架AdminLTE</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="126.html"
                               class="list-group-item">10.资产总表</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="127.html"
                               class="list-group-item">11.资产详细页面</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="128.html"
                               class="list-group-item">12.dashboard仪表盘</a>
                            
                        
                
            
          </div>
        </div>
        <!-- 左侧目录栏 结束 -->

        <!-- 右侧正文栏 -->
        <div class="col-md-9">
            <!-- 教程正文主体部分 -->
            <div class="row">
                <h1>关系类型字段</h1>
                <p>阅读:&nbsp;4136</p>
                <hr/>
                <p>除了我们前面说过的普通类型字段，Django还定义了一组关系类型字段，用来表示模型与模型之间的关系。</p>
<h2 id="foreignkey">一、多对一（ForeignKey）</h2>
<p>多对一的关系，通常被称为外键。外键字段类的定义如下：</p>
<div class="codehilite"><pre><span></span><span class="kr">class</span> <span class="nx">ForeignKey</span><span class="p">(</span><span class="nx">to</span><span class="p">,</span> <span class="nx">on_delete</span><span class="p">,</span> <span class="o">**</span><span class="nx">options</span><span class="p">)[</span><span class="nx">source</span><span class="p">]</span>
</pre></div>


<p>外键需要两个位置参数，一个是关联的模型，另一个是<code>on_delete</code>选项。实际上，在目前版本中，<code>on_delete</code>选项也可以不设置，但Django极力反对如此，因此在Django2.0版本后，该选项会设置为必填。</p>
<p><strong>外键要定义在‘多’的一方！</strong></p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">manufacturer</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="s1">&#39;Manufacturer&#39;</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="c1"># ...</span>

<span class="k">class</span> <span class="nc">Manufacturer</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="k">pass</span>
</pre></div>


<p>上面的例子中，每辆车都会有一个生产工厂，一个工厂可以生产N辆车，于是用一个外键字段manufacturer表示，并放在Car模型中。注意，此manufacturer非彼Manufacturer模型类，它是一个字段的名称。在Django的模型定义中，经常出现类似的英文单词大小写不同，一定要注意区分！</p>
<p>如果要关联的对象在另外一个app中，可以显式的指出。下例假设Manufacturer模型存在于production这个app中，则Car模型的定义如下：</p>
<div class="codehilite"><pre><span></span><span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">manufacturer</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="s1">&#39;production.Manufacturer&#39;</span><span class="p">,</span>      <span class="c1"># 关键在这里！！</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
    <span class="p">)</span>
</pre></div>


<p>如果要创建一个递归的外键，也就是自己关联自己的的外键，使用下面的方法：</p>
<div class="codehilite"><pre><span></span>models.ForeignKey(&#39;self&#39;, on_delete=models.CASCADE)
</pre></div>


<p>核心在于‘self’这个引用。什么时候需要自己引用自己的外键呢？典型的例子就是评论系统！一条评论可以被很多人继续评论，如下所示：</p>
<div class="codehilite"><pre><span></span><span class="k">class</span> <span class="nc">Comment</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">title</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
    <span class="n">text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>
    <span class="n">parent_comment</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="s1">&#39;self&#39;</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="c1"># .....</span>
</pre></div>


<p>注意上面的外键字段定义的是父评论，而不是子评论。为什么呢？因为外键要放在‘多’的一方！</p>
<p>在实际的数据库后台，Django会为每一个外键添加<code>_id</code>后缀，并以此创建数据表里的一列。在上面的工厂与车的例子中，Car模型对应的数据表中，会有一列叫做<code>manufacturer_id</code>。但实际上，在Django代码中你不需要使用这个列名，除非你书写原生的SQL语句，一般我们都直接使用字段名<code>manufacturer</code>。</p>
<p>关系字段的定义还有个小坑。在后面我们会讲到的<code>verbose_name</code>参数用于设置字段的别名。很多情况下，为了方便，我们都会设置这么个值，并且作为字段的第一位置参数。但是对于关系字段，其第一位置参数永远是关系对象，不能是<code>verbose_name</code>，一定要注意！</p>
<h3 id="_1">参数说明：</h3>
<p>外键还有一些重要的参数，说明如下：</p>
<h3 id="on_delete">on_delete</h3>
<p>当一个被外键关联的对象被删除时，Django将模仿<code>on_delete</code>参数定义的SQL约束执行相应操作。比如，你有一个可为空的外键，并且你想让它在关联的对象被删除时，自动设为null，可以如下定义：</p>
<div class="codehilite"><pre><span></span><span class="n">user</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
    <span class="n">User</span><span class="p">,</span>
    <span class="n">models</span><span class="o">.</span><span class="n">SET_NULL</span><span class="p">,</span>
    <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>


<p>该参数可选的值都内置在<code>django.db.models</code>中，包括：</p>
<ul>
<li>CASCADE：模拟SQL语言中的<code>ON DELETE CASCADE</code>约束，将定义有外键的模型对象同时删除！（该操作为当前Django版本的默认操作！）</li>
<li>PROTECT:阻止上面的删除操作，但是弹出<code>ProtectedError</code>异常</li>
<li>SET_NULL：将外键字段设为null，只有当字段设置了<code>null=True</code>时，方可使用该值。</li>
<li>SET_DEFAULT:将外键字段设为默认值。只有当字段设置了default参数时，方可使用。</li>
<li>DO_NOTHING：什么也不做。</li>
<li>SET()：设置为一个传递给SET()的值或者一个回调函数的返回值。注意大小写。</li>
</ul>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.contrib.auth</span> <span class="kn">import</span> <span class="n">get_user_model</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">def</span> <span class="nf">get_sentinel_user</span><span class="p">():</span>
    <span class="k">return</span> <span class="n">get_user_model</span><span class="p">()</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s1">&#39;deleted&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>

<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">user</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="n">settings</span><span class="o">.</span><span class="n">AUTH_USER_MODEL</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">SET</span><span class="p">(</span><span class="n">get_sentinel_user</span><span class="p">),</span>
    <span class="p">)</span>
</pre></div>


<h3 id="limit_choices_to">limit_choices_to</h3>
<p>该参数用于限制外键所能关联的对象，只能用于Django的ModelForm（Django的表单模块）和admin后台，对其它场合无限制功能。其值可以是一个字典、Q对象或者一个返回字典或Q对象的函数调用，如下例所示：</p>
<div class="codehilite"><pre><span></span><span class="n">staff_member</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
    <span class="n">User</span><span class="p">,</span>
    <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
    <span class="n">limit_choices_to</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;is_staff&#39;</span><span class="p">:</span> <span class="bp">True</span><span class="p">},</span>
<span class="p">)</span>
</pre></div>


<p>这样定义，则ModelForm的<code>staff_member</code>字段列表中，只会出现那些<code>is_staff=True</code>的Users对象，这一功能对于admin后台非常有用。</p>
<p>可以参考下面的方式，使用函数调用：</p>
<div class="codehilite"><pre><span></span><span class="k">def</span> <span class="nf">limit_pub_date_choices</span><span class="p">():</span>
    <span class="k">return</span> <span class="p">{</span><span class="s1">&#39;pub_date__lte&#39;</span><span class="p">:</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="o">.</span><span class="n">utcnow</span><span class="p">()}</span>

<span class="c1"># ...</span>
<span class="n">limit_choices_to</span> <span class="o">=</span> <span class="n">limit_pub_date_choices</span>
<span class="c1"># ...</span>
</pre></div>


<h3 id="related_name">related_name</h3>
<p>用于关联对象反向引用模型的名称。以前面车和工厂的例子解释，就是从工厂反向关联到车的关系名称。</p>
<p>通常情况下，这个参数我们可以不设置，Django会默认以模型的小写作为反向关联名，比如对于工厂就是<code>car</code>，如果你觉得<code>car</code>还不够直观，可以如下定义：</p>
<div class="codehilite"><pre><span></span><span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">manufacturer</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="s1">&#39;production.Manufacturer&#39;</span><span class="p">,</span>      
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
        <span class="n">related_name</span><span class="o">=</span><span class="s1">&#39;car_producted_by_this_manufacturer&#39;</span><span class="p">,</span>  <span class="c1"># 看这里！！</span>
    <span class="p">)</span>
</pre></div>


<p>也许我定义了一个蹩脚的词，但表达的意思很清楚。以后从工厂对象反向关联到它所生产的汽车，就可以使用<code>maufacturer.car_producted_by_this_manufacturer</code>了。</p>
<p>如果你不想为外键设置一个反向关联名称，可以将这个参数设置为“+”或者以“+”结尾，如下所示：</p>
<div class="codehilite"><pre><span></span><span class="n">user</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
    <span class="n">User</span><span class="p">,</span>
    <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
    <span class="n">related_name</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>


<h3 id="related_query_name">related_query_name</h3>
<p>反向关联查询名。用于从目标模型反向过滤模型对象的名称。（过滤和查询在后续章节会介绍）</p>
<div class="codehilite"><pre><span></span><span class="k">class</span> <span class="nc">Tag</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">article</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="n">Article</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
        <span class="n">related_name</span><span class="o">=</span><span class="s2">&quot;tags&quot;</span><span class="p">,</span>
        <span class="n">related_query_name</span><span class="o">=</span><span class="s2">&quot;tag&quot;</span><span class="p">,</span>       <span class="c1"># 注意这一行</span>
    <span class="p">)</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">)</span>

<span class="c1"># 现在可以使用‘tag’作为查询名了</span>
<span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">tag__name</span><span class="o">=</span><span class="s2">&quot;important&quot;</span><span class="p">)</span>
</pre></div>


<h3 id="to_field">to_field</h3>
<p>默认情况下，外键都是关联到被关联对象的主键上（一般为id）。如果指定这个参数，可以关联到指定的字段上，但是该字段必须具有<code>unique=True</code>属性，也就是具有唯一属性。</p>
<h3 id="db_constraint">db_constraint</h3>
<p>默认情况下，这个参数被设为True，表示遵循数据库约束，这也是大多数情况下你的选择。如果设为False，那么将无法保证数据的完整性和合法性。在下面的场景中，你可能需要将它设置为False：</p>
<ul>
<li>有历史遗留的不合法数据，没办法的选择</li>
<li>你正在分割数据表</li>
</ul>
<p>当它为False，并且你试图访问一个不存在的关系对象时，会抛出DoesNotExist 异常。</p>
<h3 id="swappable">swappable</h3>
<p>控制迁移框架的动作，如果当前外键指向一个可交换的模型。使用场景非常稀少，通常请将该参数保持默认的True。</p>
<h2 id="manytomanyfield">二、多对多（ManyToManyField）</h2>
<p>多对多关系在数据库中也是非常常见的关系类型。比如一本书可以有好几个作者，一个作者也可以写好几本书。多对多的字段可以定义在任何的一方，请尽量定义在符合人们思维习惯的一方，但不要同时都定义。</p>
<div class="codehilite"><pre><span></span><span class="kr">class</span> <span class="nx">ManyToManyField</span><span class="p">(</span><span class="nx">to</span><span class="p">,</span> <span class="o">**</span><span class="nx">options</span><span class="p">)[</span><span class="nx">source</span><span class="p">]</span>
</pre></div>


<p>多对多关系需要一个位置参数：关联的对象模型。它的用法和外键多对一基本类似。</p>
<p><strong>在数据库后台，Django实际上会额外创建一张用于体现多对多关系的中间表</strong>。默认情况下，该表的名称是“多对多字段名+关联对象模型名+一个独一无二的哈希码”，例如‘author_books_9cdf4’，当然你也可以通过<code>db_table</code>选项，自定义表名。</p>
<h3 id="_2">参数说明：</h3>
<h3 id="related_name_1">related_name</h3>
<p>参考外键的相同参数。</p>
<h3 id="related_query_name_1">related_query_name</h3>
<p>参考外键的相同参数。</p>
<h3 id="limit_choices_to_1">limit_choices_to</h3>
<p>参考外键的相同参数。但是对于使用<code>through</code>参数自定义中间表的多对多字段无效。</p>
<h3 id="symmetrical">symmetrical</h3>
<p>默认情况下，Django中的多对多关系是对称的。看下面的例子：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">friends</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="s2">&quot;self&quot;</span><span class="p">)</span>
</pre></div>


<p>Django认为，如果我是你的朋友，那么你也是我的朋友，这是一种对称关系，Django不会为Person模型添加<code>person_set</code>属性用于反向关联。如果你不想使用这种对称关系，可以将symmetrical设置为False，这将强制Django为反向关联添加描述符。</p>
<h3 id="through">through</h3>
<h3 id="_3">（定义中间表）</h3>
<p>如果你想自定义多对多关系的那张额外的关联表，可以使用这个参数！参数的值为一个中间模型。</p>
<p>最常见的使用场景是你需要为多对多关系添加额外的数据，比如两个人建立QQ好友的时间。</p>
<p>通常情况下，这张表在数据库内的结构是这个样子的：</p>
<div class="codehilite"><pre><span></span>中间表的id列....模型对象的id列.....被关联对象的id列
# 各行数据
</pre></div>


<p>如果自定义中间表并添加时间字段，则在数据库内的表结构如下：</p>
<div class="codehilite"><pre><span></span>中间表的id列....模型对象的id列.....被关联对象的id列.....时间对象列
# 各行数据
</pre></div>


<p>看下面的例子：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Group</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
    <span class="n">members</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span>
        <span class="n">Person</span><span class="p">,</span>
        <span class="n">through</span><span class="o">=</span><span class="s1">&#39;Membership&#39;</span><span class="p">,</span>       <span class="c1">## 自定义中间表</span>
        <span class="n">through_fields</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;group&#39;</span><span class="p">,</span> <span class="s1">&#39;person&#39;</span><span class="p">),</span>
    <span class="p">)</span>

<span class="k">class</span> <span class="nc">Membership</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>  <span class="c1"># 这就是具体的中间表模型</span>
    <span class="n">group</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Group</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="n">person</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Person</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="n">inviter</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="n">Person</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
        <span class="n">related_name</span><span class="o">=</span><span class="s2">&quot;membership_invites&quot;</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="n">invite_reason</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">64</span><span class="p">)</span>
</pre></div>


<p>上面的代码中，通过<code>class Membership(models.Model)</code>定义了一个新的模型，用来保存Person和Group模型的多对多关系，并且同时增加了‘邀请人’和‘邀请时间’的字段。</p>
<p><strong>through参数在某些使用场景中是必须的，至关重要，请务必掌握！</strong></p>
<h3 id="through_fields">through_fields</h3>
<p>接着上面的例子。Membership模型中包含两个关联Person的外键，Django无法确定到底使用哪个作为和Group关联的对象。所以，在这个例子中，必须显式的指定<code>through_fields</code>参数，用于定义关系。</p>
<p><code>through_fields</code>参数接收一个二元元组('field1', 'field2')，field1是指向定义有多对多关系的模型的外键字段的名称，这里是Membership中的‘group’字段（注意大小写），另外一个则是指向目标模型的外键字段的名称，这里是Membership中的‘person’，而不是‘inviter’。</p>
<p>再通俗的说，就是<code>through_fields</code>参数指定从中间表模型Membership中选择哪两个字段，作为关系连接字段。</p>
<h3 id="db_table">db_table</h3>
<p>设置中间表的名称。不指定的话，则使用默认值。</p>
<h3 id="db_constraint_1">db_constraint</h3>
<p>参考外键的相同参数。</p>
<h3 id="swappable_1">swappable</h3>
<p>参考外键的相同参数。</p>
<p><strong>ManyToManyField多对多字段不支持Django内置的validators验证功能。</strong></p>
<p><strong>null参数对ManyToManyField多对多字段无效！设置null=True毫无意义</strong></p>
<h2 id="onetoonefield">三、一对一（OneToOneField）</h2>
<p>一对一关系类型的定义如下：</p>
<div class="codehilite"><pre><span></span><span class="kr">class</span> <span class="nx">OneToOneField</span><span class="p">(</span><span class="nx">to</span><span class="p">,</span> <span class="nx">on_delete</span><span class="p">,</span> <span class="nx">parent_link</span><span class="o">=</span><span class="nx">False</span><span class="p">,</span> <span class="o">**</span><span class="nx">options</span><span class="p">)[</span><span class="nx">source</span><span class="p">]</span>
</pre></div>


<p>从概念上讲，一对一关系非常类似具有<code>unique=True</code>属性的外键关系，但是反向关联对象只有一个。这种关系类型多数用于当一个模型需要从别的模型扩展而来的情况。比如，Django自带auth模块的User用户表，如果你想在自己的项目里创建用户模型，又想方便的使用Django的认证功能，那么一个比较好的方案就是在你的用户模型里，使用一对一关系，添加一个与auth模块User模型的关联字段。</p>
<p>该关系的第一位置参数为关联的模型，其用法和前面的多对一外键一样。</p>
<p>如果你没有给一对一关系设置<code>related_name</code>参数，Django将使用当前模型的小写名作为默认值。</p>
<p>看下面的例子：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="c1"># 两个字段都使用一对一关联到了Django内置的auth模块中的User模型</span>
<span class="k">class</span> <span class="nc">MySpecialUser</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">user</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">OneToOneField</span><span class="p">(</span>
        <span class="n">settings</span><span class="o">.</span><span class="n">AUTH_USER_MODEL</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="n">supervisor</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">OneToOneField</span><span class="p">(</span>
        <span class="n">settings</span><span class="o">.</span><span class="n">AUTH_USER_MODEL</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
        <span class="n">related_name</span><span class="o">=</span><span class="s1">&#39;supervisor_of&#39;</span><span class="p">,</span>
    <span class="p">)</span>
</pre></div>


<p>这样下来，你的User模型将拥有下面的属性：</p>
<div class="codehilite"><pre><span></span>&gt;&gt;&gt; user = User.objects.get(pk=1)
&gt;&gt;&gt; hasattr(user, &#39;myspecialuser&#39;)
True
&gt;&gt;&gt; hasattr(user, &#39;supervisor_of&#39;)
True
</pre></div>


<p>OneToOneField一对一关系拥有和多对一外键关系一样的额外可选参数，只是多了一个parent_link参数。</p>
<hr />
<p>跨模块的模型：</p>
<p>有时候，我们关联的模型并不在当前模型的文件内，没关系，就像我们导入第三方库一样的从别的模块内导入进来就好，如下例所示：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">geography.models</span> <span class="kn">import</span> <span class="n">ZipCode</span>

<span class="k">class</span> <span class="nc">Restaurant</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="n">zip_code</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="n">ZipCode</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">SET_NULL</span><span class="p">,</span>
        <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
        <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="p">)</span>
</pre></div>
            </div>
            <!-- 教程正文主体部分结束 -->

            <hr />


            <!-- 打赏部分开始 -->

















            <!-- 打赏部分结束 -->


            <!-- 教程导航条 -->
            <div class="row">
                
                    <a class="pull-left" href="95.html">
                        <i class="glyphicon glyphicon-chevron-left"></i>模型和字段</a>
                

                
                    <a class="pull-right" href="97.html">
                        字段的参数<i class="glyphicon glyphicon-chevron-right"></i></a>
                
            </div>
            <!-- 教程导航条结束 -->


            <hr />

            <!-- 评论区-->
            

            <!-- 显示评论条数-->
            <div class="row">
                
                <h3>评论总数：  10</h3>
                <hr />
            </div>

            <!-- 评论表单区-->
            <div class="row">
                
                
                <a href="96.html">登录后方可评论</a>
                
            </div>
            <!-- 评论表单区结束-->

            <hr />

            <!-- 评论显示区-->
            <div class="row">
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tvax3.sinaimg.cn/crop.0.2.1125.1125.50/006ag9fjly8fngkfmdwz8j30v90vejuq.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >关于不显示为空的charfield</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    Littlesoldier1996
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年3月24日 04:47</em>
                                        <a href="/reply/326">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>请问博主，假如我有一个5行*6列的表，其中有的行 每一列都有数据，有的行只有其中3列有数据。那么在adminsite显示的时候，可否让那些没有值的charfield不显示呢？</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >可以</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    Littlesoldier1996
                                                
                                            </span>
                                        
                                        <em>2018年3月24日 09:59</em>
                                        <a href="/reply/327">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>参考http://www.liujiangblog.com158.html</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 8em">
                        <div>
                            <img src="http://tvax3.sinaimg.cn/crop.0.2.1125.1125.50/006ag9fjly8fngkfmdwz8j30v90vejuq.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >关于不显示为空的charfield的问题</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    Littlesoldier1996
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                            </span>
                                        
                                        <em>2018年3月28日 00:15</em>
                                        <a href="/reply/335">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>博主您好，我看了您发给我的链接。其中exclude可以不显示某一特定的列，但是我想实现的是仅显示一列中有值的内容，而不显示没有值的内容。请问用什么方法可以做到呢？</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 12em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >6. ModelAdmin.empty_value_display</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    Littlesoldier1996
                                                
                                            </span>
                                        
                                        <em>2018年3月28日 09:02</em>
                                        <a href="/reply/336">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>ModelAdmin.empty_value_display</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 16em">
                        <div>
                            <img src="http://tvax3.sinaimg.cn/crop.0.2.1125.1125.50/006ag9fjly8fngkfmdwz8j30v90vejuq.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >关于empty_value_display的问题</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    Littlesoldier1996
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                            </span>
                                        
                                        <em>2018年3月28日 17:22</em>
                                        <a href="/reply/339">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>谢谢您的回复。但是我查到的关于empty_value_display的用法只是说这个可以改变empty value的显示形式（比如‘None’或者其他自定义形式）但是没有说可以不显示，请问是需要override这个类吗？</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 20em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >你把这个属性值设置为空字符串不就可以了吗？</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    Littlesoldier1996
                                                
                                            </span>
                                        
                                        <em>2018年3月29日 08:32</em>
                                        <a href="/reply/342">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>灵活一下...</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tvax4.sinaimg.cn/crop.0.0.960.960.50/006xIWURly8fo9wxo24vzj30qo0qoaaz.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >问题</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    蔷薇-Nina
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年3月12日 22:32</em>
                                        <a href="/reply/299">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>为什么models.OneToOneField(to=User)，若加上参数to_field=User.name则报错？（注：User.name已设为唯一约束）</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >要看报错的具体提示信息</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    蔷薇-Nina
                                                
                                            </span>
                                        
                                        <em>2018年3月13日 08:34</em>
                                        <a href="/reply/302">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>问题描述不清晰。根据报错信息具体分析吧。</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/default/images/default_avatar_male_50.gif" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >有了on_delete属性，有没有on_update这种属性？</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    王蕾-wl
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年1月22日 11:31</em>
                                        <a href="/reply/148">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>对应mysql外键的on delete， on update 关键字</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >没有</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    王蕾-wl
                                                
                                            </span>
                                        
                                        <em>2018年1月22日 21:57</em>
                                        <a href="/reply/149">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>没有</p>
                        </div>
                    </div>
                
            </div>
            <!-- 评论显示区结束-->

            <!-- 评论区结束-->

        </div>
        <!-- 右侧正文栏结束 -->

      </div>
    </div>




    <div id="back-to-top" >
        <span class="glyphicon glyphicon-arrow-up"></span>
    </div>


    <footer id="footer" class="midnight-blue">
        <div class="container-fluid" style="font-size: smaller">
            <div class="row footer-1">
                <div class="col-md-2">
                    Copyright &copy; 2018.刘江的官方网站
                </div>
                <div class="col-md-3">
                    托管于<a target="_blank" href="https://www.aliyun.com/">阿里云</a>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <a target="_blank" href="http://www.miitbeian.gov.cn/">京ICP备17055098号</a>
                </div>
                <div class="col-md-2">
                    <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010602120033">

                        <span><img style="display: inline;margin: 0 auto;" src="/static/images/ghs.png" />京公网安备11010102002019号</span>
                    </a>
                </div>
                <div class="col-md-5">
                    <ul class="pull-right">
                        <li><a href="/blog/">返回首页</a></li>
                        <li><a href="/about/">关于博主</a></li>
                        <li><a href="#">常见问题</a></li>
                        <li><a href="/contact/" target="_blank">广告合作</a></li>
                        <li><a href="/contact/" target="_blank">联系方式</a></li>
                        <li><a href="#">使用许可</a></li>
                    </ul>
                </div>
            </div>







        </div>
    </footer><!--/#footer-->

    <script src="/static/js/jquery.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>


    <script>


        //为新闻添加访问量
        function count_visiting(news_id){
            var to_url = "/news/visiting/"+news_id;
            jQuery.get(to_url);
        }


        $("#donate").click(function () {
            $("#donate_page").toggleClass('hidden');
        });



        <!-- 导航条对应条目active -->
        $(document).ready(function () {

            $('.navbar-nav').find('a').each(function () {
                if (this.href == document.location.href || document.location.href.search(this.href) >= 0) {
                    $(this).parent().addClass('active'); // this.parent.className = 'active';
                }
            });

            $('table').addClass('table table-bordered table-hover');

            $('img').addClass('img-responsive');

            $('#back-to-top').click(function () {
                window.scrollTo(0,0);
            });

        });

    

        $('button.navbar-toggle').click(function () {
            $('#my-navbar').css("background","#337ab7")
        });
        
    </script>

</body>

</html>